package com.guigu.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.guigu.eduservice.entity.Permission;
import com.guigu.eduservice.entity.Role;
import com.guigu.eduservice.entity.RolePermission;
import com.guigu.eduservice.mapper.PermissionMapper;
import com.guigu.eduservice.mapper.RoleMapper;
import com.guigu.eduservice.mapper.RolePermissionMapper;
import com.guigu.eduservice.service.PermissionService;
import com.guigu.eduservice.service.RolePermissionService;
import com.guigu.eduservice.service.RoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guigu.eduservice.vo.RoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色表（用于RBAC权限控制） 服务实现类
 * </p>
 *
 * @author janecraft
 * @since 2025-09-27
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private  RoleService roleService;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Autowired
    private PermissionMapper permissionMapper;


    @Override
    public PageInfo<Role> getRolePage(Integer PageNo, Integer PageSize, RoleVo vo) {
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        if(vo.getRoleNameVo()!="" &&vo.getRoleNameVo()!=null){
            wrapper.like("role_name",vo.getRoleNameVo());
        }
        PageHelper.startPage(PageNo,PageSize);
        List<Role> list = roleService.list(wrapper);
        PageInfo<Role> rolePageInfo = new PageInfo<>(list);
        return rolePageInfo;
    }

    //添加角色表数据
    @Override
    public boolean addRoleWithPermissions(Role role, List<Long> permissionIds) {
        boolean save = roleService.save(role);
        if(save!=true){
            return false;
        }
        ArrayList<RolePermission> rolePermissions = new ArrayList<>();
        for (Long permissionId :permissionIds) {
            RolePermission rp = new RolePermission();
            rp.setRoleId(role.getRoleId());
            rp.setPermissionId(permissionId);
            rp.setCreateTime(LocalDateTime.now());
            rolePermissions.add(rp);
        }
        int insertRpResult =rolePermissionMapper.batchInsert(rolePermissions);
        return insertRpResult == permissionIds.size();
    }

    //修改角色表
    @Override
    public boolean updateRoleWithPermissions(Role role) {
        // 步骤1：更新角色基本信息
        boolean b = roleService.updateById(role);
        if (b!=true) {
            return false;
        }

        // 步骤2：删除旧的角色-权限关联
        rolePermissionMapper.deleteRolePermission(role.getRoleId());

        // 步骤3：批量插入新的角色-权限关联
        List<RolePermission> rolePermissionList = new ArrayList<>();
        for (Long permissionId : role.getGetPermissionIds()) {
            RolePermission rp = new RolePermission();
            rp.setRoleId(role.getRoleId());
            rp.setPermissionId(permissionId);
            rp.setCreateTime(LocalDateTime.now());
            rolePermissionList.add(rp);
        }
        int insertRpResult = rolePermissionMapper.batchInsert(rolePermissionList);
        return insertRpResult == role.getGetPermissionIds().size();
    }

    //根据角色id连接查询角色权限表和权限表
    @Override
    public Role getRoleWithPermissions(Long roleId) {
        // 查询角色基本信息
        Role role = roleService.getById(roleId);
        // 查询角色已关联的权限列表
        List<Permission> permissions = permissionMapper.getPermissionsByRoleId(roleId);
        // 提取权限ID列表（用于前端回显多选框）
        List<Long> permissionIds = permissions.stream()
                .map(Permission::getPermissionId)
                .collect(Collectors.toList());
        role.setGetPermissionIds(permissionIds);
        return role;
    }

    //根据角色Id删除角色权限表
    @Override
    public void deleteRolePermissionsByRoleId(Long roleId) {
        QueryWrapper<RolePermission> Wrapper = new QueryWrapper<>();
        if(roleId!=null){
            Wrapper.eq("role_id",roleId);
        }
        rolePermissionMapper.delete(Wrapper);
    }
}
